package com.hxzy.rabbitmqmanualconsumer.consumer;

import com.hxzy.common.QueueConst;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author wy
 * @Description 消费者（消费queue02-手动消息）
 * @Date 2024/2/21 14:53
 * @Version 1.0
 */
@Log4j2
@Component
public class Queue02Consumer {

    @Autowired
    private org.springframework.data.redis.core.RedisTemplate  redisTemplate;



    /**
     * *
     * @param message  消息
     * @param channel  消息确认通道
     */
    @RabbitListener(queues = {QueueConst.QUEUE02})
    @RabbitHandler
    public void consumer(Message  message, Channel channel) throws IOException {


        try {
            //处理消息
            String msg=new String(message.getBody());

            //要进行消息唯一性的验证(幕等性的操作)
            String uuid= message.getMessageProperties().getMessageId();
            String redisKey="queue02:execute";
            //set集合中已经有uuid了，消息已经处理过了，不要再处理了
            boolean  exists = this.redisTemplate.opsForSet().isMember(redisKey,uuid);
            if(exists){
                //确认
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }else{

                log.info("处理消息："+msg);
                this.redisTemplate.opsForSet().add(redisKey,uuid);
                //确认
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
            //写入到redis中，判断，redis是否处理过，如果有不允许再操作了
        }catch (Exception e){
            log.error(e);
            //把消息重新放到消息队列中
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
    }


}
